# -*- coding: utf-8 -*-
import time

from common.logger import Logger
from mq.queue import M_QUEUE, SUBSCRIBERS
from common.thread_util import thread_start

LOGGER = Logger(__name__)


class Job:
    """
    消息发送作业
    """
    def __init__(self):
        thread_start(target=self.start)

    def start(self):
        while True:
            if len(M_QUEUE) == 0:
                time.sleep(0.5)
            else:
                # m = M_QUEUE.pop(0)
                try:
                    for i, m in enumerate(M_QUEUE):
                        # print(jsonpickle.dumps(m.__dict__))
                        for sub in SUBSCRIBERS:
                            if sub["topic"] == m.topic:
                                # a = Message(m.topic, m.code, m.data)
                                thread_start(target=sub["consumer"], args=(m,))
                                if len(M_QUEUE) > 0:
                                    M_QUEUE.pop(i)  # del m
                except Exception as e:
                    LOGGER.error(e)


mq_job = Job()
